import java.util.Arrays;

/**
 * @author WangTianyi
 * @create 2021-12-08 19:51
 */
public class SelectionSort {
    public static void main(String[] args) {
        Integer[] array1 = new Integer[100];
        Integer[] array2 = new Integer[100];
        for (int i = 0; i < array1.length; i++) {
            array1[i] = array2[i] = (int) (Math.random()*(100-0+1));
        }
        selectionSort(array1);
        System.out.println(Arrays.toString(array1));
    }


    public static <T extends Comparable> void selectionSort(T[] array){
        int minIndex;//存储每一轮遍历时找到的该轮最小元素的下标
        for (int i = 0; i < array.length-1; i++) {
            for(int j=i+1; j< array.length; j++){
                if(array[j].compareTo(array[i])<0){ //保持稳定性，所以当值相等时不交换，只有小于的时候才交换
                    swap(array, j, i);//每次交换
                }
            }
        }
    }

    public static <T extends Comparable> void selectionSortPro(T[] array){
        int minIndex;//存储每一轮遍历时找到的该轮最小元素的下标
        for (int i = 0; i < array.length-1; i++) {
            minIndex = i;
            for(int j=i+1; j< array.length; j++){
                if(array[j].compareTo(array[minIndex])<0){ //保持稳定性，所以当值相等时不交换，只有小于的时候才交换
                    minIndex = j;
                }
            }
            swap(array, i, minIndex);
        }
    }



    public static <T extends Comparable> void swap(T[] array, int indexi, int indexj){
        T temp = array[indexi];
        array[indexi] = array[indexj];
        array[indexj] = temp;
    }
}
